from django.contrib.auth.models import User
from django.contrib import auth
from .models import Article
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import ArticleSerializer
from backend.views import get_first_error
from django.views.decorators.csrf import csrf_exempt

from rest_framework.authentication import SessionAuthentication, BasicAuthentication


class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening


# Create your views here.


class Articles(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def post(self, request):
        context = dict()
        if not request.user.is_authenticated:
            context['error'] = "您还未登录，请先登录"
            context['err_code'] = 1001
            pass
        else:
            data = request.POST
            article = Article()
            article.auth = request.user
            article.content = data.get('content')
            article.title = data.get('title')
            article.save()
            context['err_code']=0
        return Response(context)

    def get(self, request):
        context = dict()
        if not request.user.is_authenticated:
            context['err_code'] = 1001
            context['error'] = "您还未登录，请先登录"
            pass
        else:  # 已经登录
            id = request.GET.get('id')
            if id is None:
                context['error'] = "请求参数不正确"
                context['err_code'] = 2001
            else:
                article = Article.objects.filter(id=id)
                if not article.exists():  # 要的文章不存在
                    context['error'] = "无法找到您要的文章"
                    context['err_code'] = 4004
                else:
                    article_serializer = ArticleSerializer(article[0])
                    if request.user != article.auth:  # 不是自己的
                        context['error'] = "没有权限查看"
                        context['err_code'] = 4003
                    else:
                        context['err_code']=0
                        context['data']=article_serializer.data
        return Response(context)
